/**
 * @author flashflexpro@gmail.com
 * Date: 11-7-3
 * Time: 下午8:46
 */
package com.flashflexpro.testlocalconnection.view{
    import flash.events.TimerEvent;
    import flash.net.LocalConnection;
    import flash.utils.Timer;

    [Bindable]
    public class TimedCaller{
        public function TimedCaller( clientNum:int ){
            _clientNum = clientNum;
        }


        private var _timer:Timer;

        private var _clientNum:int;


        private var _toCall:Function;
        private var _toCallArgs:Array;

        public function callWhenTime( func:Function, args:Array ):void{
            _toCall = func;
            _toCallArgs = args;
            callInNextTime();
        }

        private function callInNextTime():void{
            var now:Number = new Date().getTime();

            var passed:Number = now % 1000 - _clientNum * 100;
            var wait:int = -1;

            if( passed > 100 ){
                wait = 1000 - passed +( passed % 100 );
                _timer = new Timer( wait, 1 );
                _timer.addEventListener( TimerEvent.TIMER_COMPLETE, onTimeUp );
                _timer.start();
            }
            else{
                _toCall.apply( null, _toCallArgs );
            }
            trace( "now: " + now + "; passed: " + passed + "; wait: " + wait);

        }

        private function onTimeUp( event:TimerEvent ):void{
            _timer.removeEventListener( TimerEvent.TIMER_COMPLETE, onTimeUp );
            _timer = null;
            callInNextTime();
        }

    }
}
